var markBg=$("#mark-bg");
/*初始化遮罩层的高度*/
markBg.height($(window).height());
$(window).resize(function(){
    markBg.height($(window).height());
});
/*公共弹窗js*/
/*参数说明
 *str，主要是区别公共弹窗还是其它弹窗。值目前可选"alert"、"login"、"share"、"album"、"ubsave","invite","invite-success";
 *txt，提示文字
 *btns，传入方法中的按钮html片断。考虑到有确定操作后会有其实方法的绑定，以及按钮数量不一定是两个，故整块抽出来，由使用者自定义;
 *closeMark，是否关闭背景 closeMark=false时不关闭，其它情况都关闭;
 *调用示例：showPop({str:"alert",txt:'该套装已经为您搭配了精美的封面图，保存后原封面图会被替换！',btns:'<a class="cancel" href="javascript:void(0)" onclick="hidePop(\'alert\')">取消</a><a class="sure" href="javascript:void(0)">确定</a>');
 *调用示例2：showPop({str:"login"});
 */
function showPop(obj){
    this.str=obj.str;
    this.tit=obj.tit;
    this.txt=obj.txt;
    this.btns=obj.btns;
    var closeMark=obj.closeMark;
    var pop=$("#pop-"+this.str);
    var popClose=pop.find(".close")
    markBg.show(); 
    if(this.str=="alert"){       
        var html=' <em></em><span class="txt">'+this.txt+'</span>';
        $("#alert-bd").html(html);
        $("#pop-btns").html(this.btns);
        pop.find(".pop-th .tit").html(this.tit);
    }else{
    	pop.find(".pop-th .tit").html(this.tit);
    }
    pop.show();
    popClose.click(function(){
        pop.hide();
        if(closeMark!=false){
            markBg.hide();
        }
    	if(obj.str=="login-sucess"){
    		showGuide(obj.isClubAdmin, obj.isLookedAdminGuide, obj.isLookedMemberGuide, obj.isMember);
        }
    })
}
function hidePop(str,type){
    var pop=$("#pop-"+str);
    pop.hide();
    if(type!="1"){
        markBg.hide();
    }    
}
			
/*登录弹窗js*/ 
function cheacaptcha() {
    if($("input[name='username']").val() == "用户名/邮箱/手机号") {
        $(".rTips").html("用户名和密码必须输入");
        return false;
    }
			 
    if($("input[name='password']").val() == "") {
        $(".rTips").html("用户名和密码必须输入");
        return false;
    }
			 
    if ($("#checaptcha").val() == "") {
        $(".rTips").html("请输入验证码");
        return false;
    } else {
		$("#loginForm input[name=return]").val(window.location.href);
        $("#loginform").submit();
    }
}
			
function copyText(clipId,btnId,text,popId,callback){
    if(window['clip'+clipId]){
        window['clip'+clipId].show();
        return;
    }
    ZeroClipboard.setMoviePath("/js/ZeroClipboard.swf");
    var clip = new ZeroClipboard.Client();
    clip.setHandCursor(true);          
    clip.addEventListener('mouseOver', function (client) {
        clip.setText(text);
    });
				  
    clip.addEventListener('complete', function (client, text) {
        callback();
    });
    clip.glue(btnId,popId);
    window['clip'+btnId]=clip;
}
			
function initInviteUrl(me){
    /*一键邀请的弹窗*/
    $(".showInviteDialogBtn").live('click',initInvite);
    function initInvite(){
        $.get(me.root+"/club/createInviteLink.do",{
            clubId:me.clubId
        },function(data){
            if(data.code == -1){
            	 alertErrorTip(data.message);
            }else{
				var copy = "我在中国车友会平台创建了——"+data.clubName+"，小伙帮们只要通过QQ/微博账号就可以登录加入哦，还可以做任务领车标、应急包、充值卡等丰富礼品！"+data.inviteUrl
				var html = "";
				if(me.isAdmin == "true") {
					html = "这个是我在中国车友会平台创建的车友会，";
				} else {
					html = "我已经加入了该车友会，";
				}				
				var shareContent = html + "这里有很多车友会活动，还有车标、应急包和油卡等礼品可以领取！大家一起加入壮大我们的团队吧！^_^";
				html = html + "这里有很多车友会活动，还有车标、应急包和油卡等礼品可以领取！大家一起加入壮大我们的团队吧！"+data.inviteUrl;
	            $("#invite-Text").html(html);
	            showPop({
	                str:"invite"
	            });

				var qqurl="http://connect.qq.com/widget/shareqq/index.html?";
                var url=data.inviteUrl;
                var title=encodeURI(data.clubName);
                var desc=encodeURI(shareContent);
                var summary=encodeURI(me.summary);
				var pics=me.pics;
				var shareUrl = qqurl+"url="+url+"&title="+title+"&desc="+desc+"&summary="+summary+"&site=baidu&pics="+pics;
				$(".pop-invite .invite-btn .copy").attr('href', shareUrl);
            }
        },"json")
    }
}
				
function initJoinClubDialog(me){
    $.getJSON(me.root+"/member/getApplyInfo.do",{
        clubId:me.clubId,
        req_enc:"GBK",
        resp_enc:"GBK"
    },function(data){
        if(data.status==0){
            if(data.desc){
                alertSuccessTip(data.desc);
                return ;
            }        
            //读取个人中心的信息
            $.getJSON(me.ucRoot+"/intf/getAddressByUser.jsp?callback=?",{userId:me.userId},function(data){
            	if(data.code == 0){
	                $.getScript(me.ucRoot+"/intf/area.jsp?tag=cityId&selected="+data.domicileId+"&defaultCityTips=1");
	                //赋值申请资料信息
	                $("#name").val(data.realName);
	                var gender = data.gender == 2?1:0;
	                $("input[type=radio][name=gender][value="+gender+"]").attr("checked", true);
	                $("#tel").val(data.telephone);
            	}
            },"json");
            
            if($("#pop-apply").attr("data-init")!="true"){
                $("#name,#tel").blur(function(){
                    $(this).val($.trim($(this).val()));
                });
                $.getScript("http://js.3conline.com/min/temp/v1/dpl-related_select_v2,dpl-search_car_form.js",function(){
                    //车型查询三级联动初始
                    relatedSelect({
                        id:"bid",
                        url:"http://price.pcauto.com.cn/interface/5_3/bg/brand_json_chooser.jsp?onSales=1&t=0",
                        node:{
                            root:"brands", 
                            value:"id", 
                            text:"text",
                            custom:"id"
                        },
                        load:true
                    },
                    {
                        id:"sid",
                        url:"http://price.pcauto.com.cn/interface/5_3/bg/serial_json_chooser.jsp?onSales=1&brand=",
                        node:{
                            root:"firms", 
                            value:"id", 
                            text:"text",
                            custom:"id"
                        },
                        load:false
                    });
                });
                $("#pop-apply").attr("data-init","true");
            }
            $("#feedbackMsg").html("");
            showPop({
                str:"apply"
            });
        }else if(data.status==1){
            me.login();
        }else{
            alertErrorTip(data.desc);
        }
        me.isOpenJoinDialog=false;
    });
}

function apply(me){
	var name = $("#name").val();
	if(name != "" && name.length>10){
		  $("#feedbackMsg").html("真实姓名最长10个字符，请正确填写！");
		 return;
	}
    var bid = $('#bid option:selected').val();
    if(bid&&bid!="0"){//通过接口拿数据，默认带ID0
        $('#brandName').attr('value',$('#bid option:selected').text());
    }
    var sid = $('#sid option:selected').val();
    if(sid&&sid!="0"){//通过接口拿数据，默认带ID0
        $('#serialName').attr('value',$('#sid option:selected').text());
    }
    function setProvince(){
        //提交前设置省份
        var $provinceOption = $("#areaParentTag_cityId").find("option:selected");
        if($provinceOption.length>0 && $provinceOption.val()){
            $("#provinceId").val($provinceOption.val());
            $("#provinceName").val($provinceOption.text());
        }else{
            ;
            $("#provinceId").val(0);
            $("#provinceName").val("");
        }
    }
    function setCity(){
        var $cityOption = $("#cityId").find("option:selected");
        if($cityOption.length>0 && $cityOption.val()){
            $("#cityId").val($cityOption.val());
            $("#cityName").val($cityOption.text());
        }else{
            $("#cityId").val(0);
            $("#cityName").val("");
        }
    }
    setProvince();
    setCity();
    $("#feedbackMsg").html("请求提交中……");
    $.ajax({
        url:$("#applyform").attr("action"),
        data:$("#applyform").serialize(),
        dataType:"json",
        type:"post",
        success: function(rs){
            if(rs.status==0){
                alertSuccessTip(rs.desc);			
                hidePop("apply");
            }else if(rs.status==null && rs.code==-1){
                alertErrorTip(rs.message);		
            }else{
                $("#feedbackMsg").html(rs.desc);
            }
        },
        error:function(xmlHttpRequest, textStatus, errorThrown){
            var message = "网络错误,请联系管理员";
            if(xmlHttpRequest.status==503){
                var json = eval("("+xmlHttpRequest.responseText+")");
                message = (json.message == ""?"网络错误,请联系管理员":json.message);
            }
            alertErrorTip(message);		
        }
    });
}
/**
 * 只有传false才不判装遮罩
 */
function alertErrorTip(txt,closeMark,btnTxt){
    if(!txt){
        txt = ("保存失败");
    }
	if(!btnTxt){
		btnTxt = "确定";
	}
    var btnHtml = '<a class="sure" href="javascript:hidePop(\'alert\')">'+btnTxt+'</a>';
    if(closeMark===false){
		btnHtml = '<a class="sure" href="javascript:hidePop(\'alert\',\'1\')">'+btnTxt+'</a>';		
    }
	showPop({
        str:"alert",
        txt:txt,
		closeMark:closeMark,
        btns:btnHtml
    });
}
function alertSuccessTip(txt,callback){
    if(txt){
        $("#Jsuccess-txt").html(txt);
    }else{
        $("#Jsuccess-txt").html("保存成功");
    }
    $('#mark-bg').show();
    $("#Jsuccess").css({
        marginLeft:-$("#Jsuccess").width()/2
    }).show();
    setTimeout(function(){
        $('#Jsuccess').hide();
        $('#mark-bg').hide();
        if(callback){
            callback();
        }
    },1500)
}
			
function confirmTip(txt,funcStr){
    var btnHtml = '<a class="cancel" href="javascript:void(0)" onclick="hidePop(\'alert\')">取消</a><a class="sure" href="javascript:$func">确定</a>';
    btnHtml = btnHtml.replace("$func",funcStr);
    showPop({
        str:"alert",
        txt:txt,
        btns:btnHtml
    });
}
			
function leaveNow(url){
    hidePop("alert");
    window.location.href = url;
}
			
function initSlide($target,$control,$img,callback){
    if($target.length==1){
        if(callback)
            callback($target[0]);
        $img.attr('src',$img.attr('#src'));
    }
    if($target.length>=2){
        var m=0;
        new Slide({
            target: $target,
            control: $control,
            effect: 'slide',
            autoPlay: true,
            stay: 5000,
            onchange: function(){
                var num = $target.length;
                if(m<num){//图片只加载一次就好了
                    var nli = this.target[this.curPage].getElementsByTagName("img")[0];
                    if(nli.getAttribute("#src")) {
                        nli.src = nli.getAttribute("#src");
                        nli.removeAttribute("#src");
                    }
                }
                m++;
                if(callback)
                    callback(this.target[this.curPage]);
            }
        });                 
    }
}

function initClubPromotion(bbsRoot){
    if($('#tab2 .discount-con').length==0){
        return ;
    }
    var $target = $('#tab2 .discount-con');
    var $control = $('#tab2 .pagination .toc');
    if($target.length>0){
        initSlide($target,$control,$('#tab2 .discount-con img'));
        $target.each(function(){
            var tid = $(this).attr('data-topicId');
            var id = $(this).attr('data-id');
            var url = bbsRoot+"/intf/activity/read.do?tid={tid}";
            url = url.replace("{tid}", tid);
            if(tid != '0'){
                $.ajax({
                    type:"get",
                    dataType : "jsonp",
                    url:url,
                    success:function(data){
                        if(data.status==0){
                            $(".promotionTime-"+id).html("时间："+data.createAtMin+" 至 "+data.createAtMax);
                            var pNum = data.persons==0?"不限":data.persons+"";
                            $(".promotionSign-"+id).html("已报名：<em>"+data.signUpCount+"</em>/"+pNum);
                        }else{
                            console.log("error "+tid+" "+data.desc);
                        }
                    },
                    error:function(){
                    }
                });
            }
        }); 
    }
}			
function initGoToTop(){
    if(window.screen.width <= 1024){
        $("floatBtns").style.display="none";
    }
    else{
        $("#floatBtns").show()
    }
    window.onscroll=window.onresize=function(){
        var top = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;              
        var goTop =$('#JgoTop');              
        if(top > 600){
            goTop.css("display","block");
        }else{
            goTop.css("display","none");
        }
    }
    
    $("#floatBtns .btn").hover(
        function(){
            $(this).addClass("hover");   
        },
        function(){
            $(this).removeClass("hover");   
        });
}
function goToTopConnect(){
    var img = new Image;
    img.src = "http://acount.pcauto.com.cn/wzcount/artbrowse.php?id=CNT1338&response=1";
}
function initHover(me){
    if(!me.isUpClub){
		    	/*鼠标经过变hover*/
			  $(".level").mouseover(function(){
			    $(this).find(".tips,i").show();
			})
			$(".level .tips").hover(function(){
			     $(this).show();
			    $(this).next("i").show();
			},function(){
			     $(this).hide();
			     $(this).next("i").hide();
			})
    }
    /*被锁车友会的提示语*/
    $(".look").hover(function(){
        $("#showlock").show()
    },function(){
        $("#showlock").hide();
    })
}

function showGuide(isClubAdmin,isLookedAdminGuide,isLookedMemberGuide,isMember){
	if(isMember){
		 if(isClubAdmin){
	      	if(isLookedAdminGuide == 0){	        		
	      	  $("#JpopPoint1").show();
	      	  var fp=$("#club-nav");
	      	  var $points=$(".popPoint .point");
	          var top1 =fp[0].getBoundingClientRect().top - $points.eq(0)[0].getBoundingClientRect().top+11;
			  setScroll(top1,$points.eq(0));
	      	  $('#mark-bg').show();
	      	  $.post("/member/updateGuide.do", { }, function(data) {});
	       }
	      }else{
	      	if(isLookedMemberGuide == 0){
	      	     $("#JpopPoint2").show();
	      		 var fp=$(".col-b");
	      		 var $points=$(".popPoint .point");
	      		 var top1 = fp[0].getBoundingClientRect().top - $points.eq(1)[0].getBoundingClientRect().top;
	      		 setScroll(top1,$points.eq(1));
	      	     $('#mark-bg').show();
	      	     $.post("/member/updateGuide.do", { }, function(data) {});
	      	}
	     }
	}
}

function setScroll(px,ele) {
   if (px >= 0) {
       document.documentElement.scrollTop = px;
       document.body.scrollTop = px;
       window.pageYOffset = px;
   } else {
  	    if($("#JpopPoint1").css('style')=='block'){
          $('#JpopPoint1').addClass('popPoint1Add');
       }
       else if($("#JpopPoint2").css('style')=='block'){
          $('#JpopPoint2').addClass('popPoint2Add');
       }
       else{
          ele.css("top", parseInt(ele.css("top")) + px);
       }
   }
}